package com.allianz.webapps.controllers;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.allianz.frame.utils.StringUtil;
import com.allianz.frame.utils.fedMailUtil;
import com.allianz.webapps.https.interfaces.type001.pojo.User;


@Controller
@RequestMapping(value="/feedback")
public class AppFeedBackController {
	
	@RequestMapping(value="/index")
	public String toSendMail(){
		return "views/page/fedBack";
	}
	/**
	 * 图片base64 发至统一邮箱
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/upImgFile")
	@ResponseBody
	public Object callBack(@RequestParam(value="images",required=false)String images,HttpServletRequest request,HttpSession session){
		Map<String,Object> map = new HashMap<String, Object>();
		User user=(User) request.getSession().getAttribute("username");
		List<String>  imagList =null;
		if (StringUtil.notNull(images)) {
			String[] image_list = images.split("\\|");
			imagList= Arrays.asList(image_list);
		}
		//问题截图
		//问题类型
		String reportType=request.getParameter("type");
		if ("".equals(reportType) || "请选择".equals(reportType)) {
			reportType ="其他";
		}
		//问题描述
		String reportDescribe=request.getParameter("describe");
		if (reportDescribe == null || "".equals(reportDescribe)) {
			map.put("status", "error");
			map.put("msg", "请填写反馈信息后提交!");
			return map;
		}
		//回复邮箱
		String emaila = request.getParameter("email");
		if (!checkEmaile(emaila)) {
			map.put("status", "error");
			map.put("msg", "请填写正确联系邮箱!");
			return map;
		}
		boolean flag = false;
		try {
			//发送反馈邮件
			flag = fedMailUtil.sendEmail(reportDescribe, imagList, reportType,emaila,user);
		if (!flag) {
			//失败重新发一次
			flag=	fedMailUtil.sendEmail(reportDescribe, imagList, reportType,emaila,user);
		}
		if (!flag) {
			new Exception();
		}
			map.put("status", "success");
			map.put("msg", "反馈信息已发至相关负责人邮箱!");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", "error");
			map.put("msg", "反馈信息发送失败,请联系管理人员!");
		}
		return map;
	}
	
	  /**
     * 正则表达式校验邮箱
     * @param emaile 待匹配的邮箱
     * @return 匹配成功返回true 否则返回false;
     */
    private static boolean checkEmaile(String emaile){
        String RULE_EMAIL = "^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$";
        //正则表达式的模式
        Pattern p = Pattern.compile(RULE_EMAIL);
        //正则表达式的匹配器
        Matcher m = p.matcher(emaile);
        //进行正则匹配
        return m.matches();
    }
}
